package com.oyz.web;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * @author oyz
 */
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    /** 传统的SpringMvc实现思路
     * <web-app>
     *   初始化Spring上下文
     *    <listener>
     *        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     *    </listener>
     *    指定Spring的配置文件
     *    <context-param>
     *        <param-name>contextConfigLocation</param-name>
     *        <param-value>/WEB-INF/app-context.xml</param-value>
     *    </context-param>
     *   初始化DispatcherServlet
     *    <servlet>
     *        <servlet-name>app</servlet-name>
     *        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     *        <init-param>
     *            <param-name>contextConfigLocation</param-name>
     *            <param-value></param-value>
     *        </init-param>
     *        <load-on-startup>1</load-on-startup>
     *    </servlet>
     *    <servlet-mapping>
     *        <servlet-name>app</servlet-name>
     *        <url-pattern>/app/*</url-pattern>
     *    </servlet-mapping>
     * </web-app>
     * @param servletContext
     * @throws ServletException
     */

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // Load Spring web application configuration
        //通过注解的方式初始化Spring的上下文
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        // 注册spring的配置类（替代传统项目中xml的configuration)  理解:也是为了实现可以自动通过@ComponentScan扫描Controller等组件这一步
        context.register(AppConfig.class);
        context.refresh();
        // Create and register the DispatcherServlet
        // 基于java代码的方式初始化DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(context);
        ServletRegistration.Dynamic dynamic = servletContext.addServlet("/", servlet);
        dynamic.setLoadOnStartup(1);
        dynamic.addMapping("/*");
    }
}
